<template>
    <div class="d1">
        <el-card shadow="hover" style="width:80%">
            <!--1. 搜索表单-->
            <el-form :inline="true" :model="studentSearch" class="demo-form-inline" size="medium">
                <el-form-item>
                    <el-input v-model="studentSearch.sname" placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="studentSearch.addr" placeholder="住址"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="studentSearch.cid" placeholder="所在班级">
                        <el-option label="所有班级" value="0"></el-option>
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search" icon="el-icon-search" plain>查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="addUI" icon="el-icon-plus" plain>添加</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="warning" @click="handleDelete" icon="el-icon-delete" plain>批量删除</el-button>
                </el-form-item>
            </el-form>
            <el-table
                    :data="students"
                    size="medium"
                    @selection-change="handleSelectionChange">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        label="学号"
                        prop="sid"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        prop="sname"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="性别"
                        prop="sex"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="住址"
                        prop="addr"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="年龄"
                        prop="age"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="所在班级"
                        prop="cname"
                        align="center">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button-group>
                            <el-button
                                    size="mini"
                                    icon="el-icon-edit"
                                    @click="handleEdit(scope.$index, scope.row)">
                            </el-button>
                            <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.$index, scope.row)">
                            </el-button>
                        </el-button-group>

                    </template>
                </el-table-column>
            </el-table>
            <!--3. 分页导航-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>

        <el-dialog :title="student.sid ? '修改学生' : '添加学生'" :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false">
            <el-form :model="student" :rules="rules" ref="studentRef">
                {{student}}
                <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                    <el-input v-model="student.sname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
                    <el-radio v-model="student.sex" label="男">男</el-radio>
                    <el-radio v-model="student.sex" label="女">女</el-radio>
                </el-form-item>
                <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
                    <el-input v-model.number="student.age" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
                    <el-input v-model="student.addr" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
                    <el-select v-model="student.cid" placeholder="所在班级">
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<style>

    .d1 {
        display: flex;
        justify-content: center;
    }

    .el-pagination {
        text-align: right;
        margin-top: 20px;
    }
</style>
<script>
    import {findAllStudents, search, save, delStud} from "@/api/student";
    import {findAllClasses} from "@/api/classes"

    export default {
        data() {
            // 自定义校验规则
            let myAgeValidator = (rule, value, callback) => {
                if (!value) {
                    callback(new Error("年龄不能为空！"))
                } else if (!Number.isInteger(value)) {
                    callback(new Error("年龄只能是整数！"))
                } else {
                    callback()
                }

            };
            return {
                students: [],
                studentSearch: {},
                page: 1,
                pageSize: 5,
                total: 100,
                classes: [],
                student: {},
                dialogFormVisible: false,            // 显示或隐藏表单
                formLabelWidth: '100px',
                multipleSelection:[],               // 存放选择的多个学生对象
                sids:[],                            // 用户选择的学生的编号数组
                //进行表单验证
                rules: {
                    sname: [
                        {required: true, message: '用户名必须填写！', trigger: 'blur'}
                    ],
                    sex: [
                        {required: true, message: '必须选择性别！', trigger: 'change'}
                    ],
                    age: [
                        {validator: myAgeValidator, trigger: 'blur'}
                    ],
                    addr: [
                        {required: true, message: '地址必须填写！', trigger: 'blur'}
                    ],
                    cid: [
                        {required: true, message: '必须选择所在班级！', trigger: 'change'}
                    ]

                }
            }
        },
        created() {
            //1. 查询所有学生
            // this.findAllStudents()
            //2. 条件查询带分页
            this.search()
            //3. 查询所有班级
            this.findAllClasses()
        },
        methods: {
            //1. 查询所有学生
            findAllStudents() {
                findAllStudents().then(({data}) => {
                    this.students = data.data.list
                    console.log("data:", data)
                })
            },
            //2. 条件查询带分页
            async search() {
                const {data} = await search(this.page, this.pageSize, this.studentSearch)
                this.total = data.data.pr.total
                this.students = data.data.pr.rows
            },
            //3. 查询所有班级
            async findAllClasses() {
                const {data} = await findAllClasses();
                console.log("data:classes", data)
                this.classes = data.data.list
            },
            //4. 添加学生界面
            addUI() {
                //4.1 显示对话框
                this.dialogFormVisible = true
                //4.2 清空原来的表单数据
                this.student = {}

            },
            //5. 编辑学生
            handleEdit(index, row) {
                console.log(index, row);
                this.student = row
                this.dialogFormVisible = true
                this.$refs['studentRef'].resetFields()   // 重置校验规则
            },
            //6. 添加或修改学生到数据库
            save() {
                //6.1 确定url地址
                let url = "/student/add"
                if (this.student.sid) {
                    url = "/student/update"
                }
                //6.2 如果校验通过就发出添加或修改请求
                let _this = this
                this.$refs['studentRef'].validate(valid => {
                    if (valid) {
                        save(url, this.student).then(({data}) => {
                            console.log("save:data", data)
                            if (data.code === 20000) {
                                this.$message({
                                    message: data.message,
                                    type: 'success',
                                    onClose() {
                                        //① 刷新页面
                                        _this.search()
                                        //② 关闭对话框
                                        _this.dialogFormVisible = false

                                    }
                                });
                            }
                        })
                    }
                })
            },

            //7. 删除
            handleDelete(index, row) {
                console.log(index, row);
                //7.1 确定点击的是”删除单个“还是”批量删除“按钮,可以根据row这个参数是否有值进行判断，如果有值，证明是删除单个
                if(row){
                    this.sids = [row.sid]
                }else{
                    this.sids = this.multipleSelection.map(m=>m.sid)
                }
                console.log("sids:",this.sids)
                //7.2 开始删除单个或多个
                let _this = this
                this.$confirm(`此操作将永久删除【${row ? row.sname : '所选择的学生'}】, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delStud(_this.sids).then(({data}) => {
                        if (data.code === 20000) {
                            this.$message({
                                type: 'success',
                                message: data.message,
                                onClose() {
                                    _this.search()      // 刷新页面
                                }
                            });
                        }
                    })


                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            // 点击复选框之后，将选择的哪一行放到数组multipleSelection中
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log("选择的学生：",this.multipleSelection)
            },
            // pageSize改变时触发
            handleSizeChange(val) {
                this.pageSize = val
                this.search()
                console.log(`每页 ${val} 条`);
            },
            // page改变时触发
            handleCurrentChange(val) {
                this.page = val
                this.search()
                console.log(`当前页: ${val}`);
            }
        }
    }
</script>